/*
 * Copyright (c) 2006-2020, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 */

#include <rthw.h>
#include <rtdevice.h>
#include <rtthread.h>

#include "board.h"
#include "__def.h"
#include "uart.h"

struct rt_serial_device serial0;
UART_Type *uart0;

static rt_err_t _uart_configure(struct rt_serial_device *serial, struct serial_configure *cfg)
{
    UART_Type *uart;
    uart = (UART_Type*)serial->parent.user_data;

    return (RT_EOK);
}

static rt_err_t _uart_control(struct rt_serial_device *serial, int cmd, void *arg)
{
    UART_Type *uart;
    uart = (UART_Type*)serial->parent.user_data;

    return (RT_EOK);
}

static int _uart_putc(struct rt_serial_device *serial, char c)
{
    UART_Type *uart;
    uart = (UART_Type*)serial->parent.user_data;

    uart_send_wait(uart, (uint8_t)c);

    return (1);
}

static int _uart_getc(struct rt_serial_device *serial)
{
    UART_Type *uart;
    uart = (UART_Type*)serial->parent.user_data;
    
    int ch = (int8_t)uart_read(uart);

    return ch;
}

const struct rt_uart_ops _uart_ops = {
    _uart_configure,
    _uart_control,
    _uart_putc,
    _uart_getc,
    RT_NULL
};

/*
 * UART Initiation
 */
int rt_hw_uart_init(void)
{
    struct rt_serial_device *serial;
    UART_Type *uart;

    struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT;
    
    serial = &serial0;
    uart = UART1;

    serial->ops = &_uart_ops;
    serial->config = config;

    uart = UART1;

    rt_hw_serial_register(serial,
                          RT_CONSOLE_DEVICE_NAME,
                          RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX,
                          uart);

    return 0;
}

void uart1_handler(void)
{
    rt_hw_serial_isr(&serial0, RT_SERIAL_EVENT_RX_IND); 
}
